﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace CFR.Silverlight.Scheduling
{
    public class HourPanel : Control
    {
        DispatcherTimer _currentTimer;
        
        protected internal Rectangle CurrentTimeRectangle { get; private set; }

        #region TimesToShow (DependencyProperty)

        /// <summary>
        /// This is a list of the times to show.
        /// </summary>
        public ObservableCollection<DateTime> TimesToShow
        {
            get { return (ObservableCollection<DateTime>)GetValue(TimesToShowProperty); }
            set { SetValue(TimesToShowProperty, value); }
        }
        public static readonly DependencyProperty TimesToShowProperty =
            DependencyProperty.Register("TimesToShow", typeof(ObservableCollection<DateTime>), typeof(HourPanel),
              new PropertyMetadata(null));

        #endregion

        public HourPanel()
            : base()
        {
            this.Loaded += new RoutedEventHandler(HourPanel_Loaded);
            _currentTimer = new DispatcherTimer();
            _currentTimer.Interval = new TimeSpan(0, 1, 0);
            _currentTimer.Tick += new EventHandler(_currentTimer_Tick);
            
            this.DefaultStyleKey = typeof(HourPanel);
            this.UseLayoutRounding = false;
            this.TimesToShow = new ObservableCollection<DateTime>();

            for (int i = 0; i < 48; i++)
            {
                TimesToShow.Add(DateTime.Now.Date.AddMinutes(i * 30));
            }
        }

        void HourPanel_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateCurrentTimeLocation();
        }

        void _currentTimer_Tick(object sender, EventArgs e)
        {
            UpdateCurrentTimeLocation();
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            CurrentTimeRectangle = (Rectangle)GetTemplateChild("CurrentTimeRectangle");
            UpdateCurrentTimeLocation();
            _currentTimer.Start();
        }

        private void UpdateCurrentTimeLocation()
        {
            double yOffset = GetTimeYOffset(DateTime.Now);

            CurrentTimeRectangle.Margin = new Thickness(0, yOffset, 0, 0);
        }

        public double GetTimeYOffset(DateTime dateTime)
        {
            var ticksInDay = (new TimeSpan(1,0,0,0).Ticks);

            var percent = (double)dateTime.TimeOfDay.Ticks / (double)ticksInDay;

            return ActualHeight * percent;
        }

        public void Refresh()
        {
            UpdateCurrentTimeLocation();
        }
    }
}
